const { resolve } = require('path')
const config = require('../config/config')
const api = require('../app/api')

const help = '亲爱的，欢迎关注科幻电影世界\n' +
   '回复 1 ~ 3，测试文字回复\n' +
   '回复 4，测试图文回复\n' +
   '回复 首页，进入电影首页\n' +
   '回复 电影名字，查询电影信息\n' +
   '某些功能订阅号无权限，如网页授权\n' +
   '回复 语音，查询电影信息\n' +
   '也可以点击 <a href="' + config.wechat.baseUrl + '/wechat/movie">语音查电影</a>'

exports.reply = async (ctx, next) => {
  const message = ctx.weixin

  console.log(message)

  let mp = require('../wechat')
  let client = mp.getWechat()

  const tokenData = await client.fetchAccessToken()

  console.log(tokenData)
  console.log(await client.handle('getUserInfo', message.FromUserName, tokenData.access_token))

  if (message.MsgType === 'event') {
    if (message.Event === 'subscribe') {
      ctx.body = help
    } else if (message.Event === 'unsubscribe') {
      console.log('无情取关')
      ctx.body = ''
    } else if (message.Event === 'LOCATION') {
      ctx.body = '您上报的位置是： ' + message.Latitude + '/' + message.Longitude + '-' + message.Precision
    } else if (message.Event === 'SCAN') {
      console.log('关注后扫二维码' + message.EventKey + ' ' + message.Ticket)

      ctx.body = '看到你扫了一下哦'
    } else if (message.Event === 'VIEW') {
      ctx.body = '您点击了菜单中的链接 ： ' + message.EventKey
    } else if (message.Event === 'scancode_push') {
      console.log(message.ScanCodeInfo.ScanType)
      console.log(message.ScanCodeInfo.ScanResult)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'scancode_waitmsg') {
      console.log(message.ScanCodeInfo.ScanType)
      console.log(message.ScanCodeInfo.ScanResult)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'pic_sysphoto') {
      console.log(message.SendPicsInfo.PicList)
      console.log(message.SendPicsInfo.Count)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'pic_photo_or_album') {
      console.log(message.SendPicsInfo.PicList)
      console.log(message.SendPicsInfo.Count)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'pic_weixin') {
      console.log(message.SendPicsInfo.PicList)
      console.log(message.SendPicsInfo.Count)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'location_select') {
      console.log(message.SendLocationInfo.Location_X)
      console.log(message.SendLocationInfo.Location_Y)
      console.log(message.SendLocationInfo.Scale)
      console.log(message.SendLocationInfo.Label)
      console.log(message.SendLocationInfo.Poiname)
      ctx.body = '您点击了菜单中 ： ' + message.EventKey
    } else if (message.Event === 'CLICK') {
      let news = []

      if (message.EventKey === 'movie_hot') {
        let movies = await api.movie.findHotMovies(-1, 10)

        movies.forEach((movie) => {
          news.push({
            title: movie.title,
            description: movie.title,
            picUrl: movie.poster,
            url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
          })
        })
      } else if (message.EventKey === 'movie_cold') {
        let movies = await api.movie.findHotMovies(1, 10)

        movies.forEach((movie) => {
          news.push({
            title: movie.title,
            description: movie.title,
            picUrl: movie.poster,
            url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
          })
        })
      } else if (message.EventKey === 'movie_crime') {
        let cat = await api.movie.findMoviesByCate('犯罪')

        cat.movies.forEach((movie) => {
          news.push({
            title: movie.title,
            description: movie.title,
            picUrl: movie.poster,
            url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
          })
        })
      } else if (message.EventKey === 'movie_cartoon') {
        let cat = await api.movie.findMoviesByCate('动画')

        cat.movies.forEach((movie) => {
          news.push({
            title: movie.title,
            description: movie.title,
            picUrl: movie.poster,
            url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
          })
        })
      } else if (message.EventKey === 'help') {
        news = help
      }

      ctx.body = news
    }
  } else if (message.MsgType === 'voice') {
    let voiceText = message.Recognition
    let movies = await api.movie.searchByName(voiceText)
    let reply

    if (!movies || movies.length === 0) {
      movies = await api.movie.searchByDouban(voiceText)
    }

    if (movies && movies.length > 0) {
      reply = []

      movies = movies.slice(0, 10)

      movies.forEach((movie) => {
        reply.push({
          title: movie.title,
          description: movie.title,
          picUrl: movie.poster,
          url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
        })
      })
    } else {
      reply = '没有查询到与 ' + voiceText + ' 匹配的电影，要不要换一个名字试试'
    }

    ctx.body = reply
  } else if (message.MsgType === 'text') {
    let content = message.Content
    let reply = '额，你说的 ' + message.Content + ' 太复杂了'

    if (content === '1') {
      reply = '天下第一吃大米'
    } else if (content === '2') {
      reply = '天下第二吃豆腐'
    } else if (content === '3') {
      reply = '天下第三吃仙丹'
    } else if (content === 'imooc' || content === '慕课网') {
      let user = await client.handle('getUserInfo', message.FromUserName, tokenData.access_token, 'cn')
      let name = user.nickname

      if (user.gender === 'male') {
        name = `小鲜肉 - ${name}`
      } else if (user.gender === 'female') {
        name = `软妹纸 - ${name}`
      }

      let guess = '我猜不出你来自哪里,'

      if (user.province || user.city) {
        guess = `我猜你来自${user.province}省,${user.city} 市,`
      }

      let countData = await api.user.saveWechatUser(message, 'imooc')
      let end = `${guess}哈哈，这些信息是只有你关注了我才能从微信服务器拿到，不然是拿不到的，别紧张，跟着 Scott 学习微信开发的这个课程，你也能迅速做出一个属于自己的微信应用，加油！<a href="${config.wechat.baseUrl}/imooc/promise">点点 Promise 动画</a>`

      reply = `哎呦喂！你是来自慕课网的${name}, 你有${countData.count}个来自慕课网的小伙们开始研究学习这个账号了，请温柔一点，${end}`
    } else if (content === '首页') {
      reply = [{
        title: 'https://wechat7online.iblack7.com/',
        description: 'PC 上预览效果更佳',
        picUrl: 'http://szimg.mukewang.com/56ea544a00012caf05400300-156-88.jpg',
        url: 'https://wechat7online.iblack7.com/'
      }]
    } else if (content === '4') {
      reply = [{
        title: '技术改变世界',
        description: '只是个描述而已',
        picUrl: 'http://res.cloudinary.com/moveha/image/upload/v1441184110/assets/images/Mask-min.png',
        url: 'https://github.com/'
      }, {
        title: 'Nodejs 开发微信',
        description: '爽到爆',
        picUrl: 'https://res.cloudinary.com/moveha/image/upload/v1431337192/index-img2_fvzeow.png',
        url: 'https://nodejs.org/'
      }]
    } else if (content === '5') {
      let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../2.jpg'))

      reply = {
        type: 'image',
        mediaId: data.media_id
      }
    } else if (content === '6') {
      let data = await client.handle('uploadMaterial', 'video', resolve(__dirname, '../6.mp4'))
      reply = {
        type: 'video',
        title: '回复视频内容',
        description: '打个篮球玩玩',
        mediaId: data.media_id
      }
    } else if (content === '7') {
      let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../2.jpg'))

      reply = {
        type: 'music',
        title: '回复音乐内容',
        description: '放松一下',
        // 测试号的时候，高品质音乐链接不能为空
        musicUrl: 'https://cappro.oss-cn-hangzhou.aliyuncs.com/happier.mp3',
        hqMusicUrl: 'https://cappro.oss-cn-hangzhou.aliyuncs.com/happier.mp3',
        thumbMediaId: data.media_id
      }
      console.log(reply)
    } else if (content === '8') {
      let data = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../2.jpg'), {type: 'image'})

      reply = {
        type: 'image',
        mediaId: data.media_id
      }
    } else if (content === '9') {
      let data = await client.handle('uploadMaterial', 'video', resolve(__dirname, '../6.mp4'), {type: 'video', description: '{"title": "Really a nice place", "introduction": "Never think it so easy"}'})

      reply = {
        type: 'video',
        title: '回复视频内容',
        description: '打个篮球玩玩',
        mediaId: data.media_id
      }
    } else if (content === '10') {
      let picData = await client.handle('uploadMaterial', 'image', resolve(__dirname, '../2.jpg'), {})

      let media = {
        articles: [{
          title: '这是服务端上传的图文 1',
          thumb_media_id: picData.media_id,
          author: 'Scott',
          digest: '没有摘要',
          show_cover_pic: 1,
          content: '点击阅读原文会跳到 github',
          content_source_url: 'https://github.com'
        }, {
          title: '这是服务端上传的图文 2',
          thumb_media_id: picData.media_id,
          author: 'Scott',
          digest: '没有摘要',
          show_cover_pic: 1,
          content: '点击阅读原文会跳到 github',
          content_source_url: 'https://github.com'
        }]
      }

      let data = await client.handle('uploadMaterial', 'news', media, {})
      data = await client.handle('fetchMaterial', data.media_id, 'news', {})

      console.log(data)

      let items = data.news_item
      let news = []

      items.forEach((item) => {
        news.push({
          title: item.title,
          decription: item.digest,
          picUrl: picData.url,
          url: item.url
        })
      })

      reply = news
    } else if (content === '11') {
      let counts = await client.handle('countMaterial')

      console.log(JSON.stringify(counts))

      let res = await Promise.all([
        client.handle('batchMaterial', {
          type: 'image',
          offset: 0,
          count: 10
        }),
        client.handle('batchMaterial', {
          type: 'video',
          offset: 0,
          count: 10
        }),
        client.handle('batchMaterial', {
          type: 'voice',
          offset: 0,
          count: 10
        }),
        client.handle('batchMaterial', {
          type: 'news',
          offset: 0,
          count: 10
        })
      ])

      console.log(res)

      reply = `image: ${res[0].total_count}
        video: ${res[1].total_count}
        voice: ${res[2].total_count}
        news: ${res[3].total_count}
      `
    } else if (content === '12') {
      // let group = await client.createGroup('wechat7')

      // console.log('新分组 wechat7')
      // console.log(group)

      // let groups = await client.fetchGroups()

      // console.log('加了 wechat 后的分组列表')
      // console.log(groups)

      // let group2 = await client.checkGroup(message.FromUserName)

      // console.log('查看自己的分组')

      // console.log(group2)

      // let result = await client.moveGroup(message.FromUserName, 118)
      // console.log('移动到  115')
      // console.log(result)

      // let groups2 = await client.fetchGroups()

      // console.log('移动后的分组列表')
      // console.log(groups2)

      let result2 = await client.moveGroup([message.FromUserName], 119)
      console.log('批量移动到  119')
      console.log(result2)

      let groups3 = await client.fetchGroups()

      console.log('批量移动后的分组列表')
      console.log(groups3)

      // let result3 = await client.updateGroup(117, 'wechat117')

      // console.log('117 wechat2 改名 wechat117')
      // console.log(result3)

      // let groups4 = await client.fetchGroups()

      // console.log('改名后的分组列表')
      // console.log(groups4)

      // let result4 = await client.deleteGroup(102)

      // console.log('删除 114 tututu 分组')

      // console.log(result4)

      // let groups5 = await client.fetchGroups()

      // console.log('删除 114 后分组列表')
      // console.log(groups5)

      reply = JSON.stringify(groups3)
    } else if (content === '13') {
      let user = await client.fetchUsers(message.FromUserName, 'en')

      console.log(user)

      let openIds = [
        {
          openid: message.FromUserName,
          lang: 'en'
        }
      ]

      let users = await client.fetchUsers(openIds)

      console.log(users)

      reply = JSON.stringify(user)
    } else if (content === '14') {
      let userlist = await client.listUsers()

      console.log(userlist)

      reply = userlist.total
    } else if (content === '15') {
      let text = {
        'content': 'Hello Wechat'
      }

      let msgData = await client.sendByGroup('text', text, 119)

      console.log(msgData)
      reply = 'Yeah!'
    } else if (content === '16') {
      let mpnews = {
        media_id: 'tWieFbfwczCt3AbOGNzmVzaEHNVZP2--gHMHZ01IAEo'
      }
      // let text = {
      //   'content': 'Hello Wechat'
      // }

      let msgData = await client.previewMass('mpnews', mpnews, 'okH-duBePdGVlZ3PyqJsVkBeJspw')

      console.log(msgData)
      reply = 'Yeah!'
    } else if (content === '17') {
      let msgData = await client.checkMass('400958630')

      console.log(msgData)
      reply = 'Yeah hah!'
    } else if (content === '18') {
      // let tempQr = {
      //   expire_seconds: 400000,
      //   action_name: 'QR_SCENE',
      //   action_info: {
      //     scene: {
      //       scene_id: 123
      //     }
      //   }
      // }

      // let permQr = {
      //   action_name: 'QR_LIMIT_SCENE',
      //   action_info: {
      //     scene: {
      //       scene_id: 123
      //     }
      //   }
      // }

      // let permStrQr = {
      //   action_name: 'QR_LIMIT_STR_SCENE',
      //   action_info: {
      //     scene: {
      //       scene_str: 'abc'
      //     }
      //   }
      // }

      // let qr1 = await client.createQrcode(tempQr)
      // let qr2 = await client.createQrcode(permQr)
      // let qr3 = await client.createQrcode(permStrQr)

      reply = 'Yeah hah!'
    } else if (content === '19') {
      let longUrl = 'http://www.imooc.com/'
      let shortData = await client.createShorturl(null, longUrl)

      reply = shortData.short_url
    } else if (content === '20') {
      let semanticData = {
        query: '寻龙诀',
        city: '杭州',
        category: 'movie',
        uid: message.FromUserName
      }

      let _semanticData = await client.handle('semantic', semanticData)

      reply = JSON.stringify(_semanticData)
    } else {
      let movies = await api.movie.searchByName(content)

      if (!movies || movies.length === 0) {
        movies = await api.movie.searchByDouban(content)
      }

      if (movies && movies.length > 0) {
        reply = []
        movies = movies.slice(0, 10)
        movies.forEach((movie) => {
          reply.push({
            title: movie.title,
            description: movie.title,
            picUrl: config.wechat.baseUrl + '/upload/' + movie.poster,
            url: config.wechat.baseUrl + '/wechat/jump/' + movie._id
          })
        })
      } else {
        reply = '没有查询到与 ' + content + ' 匹配的电影，要不要换一个名字试试'
      }
    }

    ctx.body = reply
  }

  await next()
}
